import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel,
                             QPushButton, QVBoxLayout, QWidget,
                             QMessageBox, QFileDialog, QInputDialog, 
                             QScrollArea, QHBoxLayout, QSlider, QSpinBox,
                             QDialog, QTextEdit, QFormLayout, QLineEdit,
                             QGroupBox, QCheckBox, QComboBox)
from PyQt5.QtGui import QPixmap, QImage, QPainter, QPen, QFont, QColor
from PyQt5.QtCore import Qt, QRect
from PIL import Image, ImageDraw, ImageFont, ImageStat
import re
from datetime import datetime
import numpy as np
import json


class ImageLabel(QLabel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_app = parent
        self.setMinimumSize(800, 600)
        self.setStyleSheet("border: 1px solid gray;")
        self.selecting = False
        self.preview_mode = False
        self.dragging_preview = False
        self.preview_text = ""
        self.preview_params = None
        self.preview_position = None
        
    def set_preview_mode(self, enabled, text="", params=None):
        """设置预览模式"""
        self.preview_mode = enabled
        self.preview_text = text
        self.preview_params = params
        if enabled and params:
            # 计算初始预览位置（选择区域的中心）
            if self.parent_app.selection_start and self.parent_app.selection_end:
                x1, y1 = self.parent_app.selection_start
                x2, y2 = self.parent_app.selection_end
                center_x = (x1 + x2) // 2
                center_y = (y1 + y2) // 2
                self.preview_position = (center_x, center_y)
        
    def mousePressEvent(self, event):
        if self.preview_mode and event.button() == Qt.LeftButton:
            # 预览模式下检查是否点击在预览文本上
            if self.preview_position and self.is_click_on_preview(event.pos()):
                self.dragging_preview = True
                self.setCursor(Qt.ClosedHandCursor)
            else:
                # 点击其他地方，退出预览模式
                self.parent_app.exit_preview_mode()
        elif not self.preview_mode and event.button() == Qt.LeftButton and self.parent_app.modified_image:
            # 正常选择模式
            self.parent_app.selection_start = (event.pos().x(), event.pos().y())
            self.parent_app.selection_end = None
            self.selecting = True
            
    def mouseMoveEvent(self, event):
        if self.preview_mode:
            if self.dragging_preview:
                # 拖拽预览文本
                self.preview_position = (event.pos().x(), event.pos().y())
                self.parent_app.update_preview_display()
            else:
                # 检查鼠标是否在预览文本上
                if self.preview_position and self.is_click_on_preview(event.pos()):
                    self.setCursor(Qt.OpenHandCursor)
                else:
                    self.setCursor(Qt.ArrowCursor)
        elif self.selecting and self.parent_app.modified_image:
            # 正常选择模式
            self.parent_app.selection_end = (event.pos().x(), event.pos().y())
            self.parent_app.drawSelection()
            
    def mouseReleaseEvent(self, event):
        if self.preview_mode and self.dragging_preview:
            self.dragging_preview = False
            self.setCursor(Qt.OpenHandCursor)
        elif event.button() == Qt.LeftButton and self.selecting:
            self.selecting = False
            if self.parent_app.selection_start and self.parent_app.selection_end:
                self.parent_app.drawSelection()
                
    def is_click_on_preview(self, pos):
        """检查点击是否在预览文本区域内"""
        if not self.preview_position or not self.preview_params:
            return False
            
        # 估算文本区域（简化计算）
        text_width = len(self.preview_text) * self.preview_params['font_size'] * 0.6
        text_height = self.preview_params['font_size'] * 1.2
        
        px, py = self.preview_position
        return (px - text_width//2 <= pos.x() <= px + text_width//2 and 
                py - text_height//2 <= pos.y() <= py + text_height//2)


class DateReplacerApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.selection_start = None
        self.selection_end = None
        self.original_image = None
        self.modified_image = None
        self.current_pixmap = None
        self.font_size = 14  # 默认字体大小
        self.last_analysis_result = None  # 存储最后一次分析结果

    def initUI(self):
        self.setWindowTitle('智能日期修改工具')
        self.setGeometry(100, 100, 1200, 900)
        self.setMinimumSize(1000, 700)

        # 创建主布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout(main_widget)

        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.btn_load = QPushButton('加载图片', self)
        self.btn_load.clicked.connect(self.loadImage)
        self.btn_load.setFixedHeight(40)

        self.btn_replace = QPushButton('替换日期', self)
        self.btn_replace.clicked.connect(self.replaceDate)
        self.btn_replace.setEnabled(False)
        self.btn_replace.setFixedHeight(40)

        self.btn_analyze = QPushButton('分析样式', self)
        self.btn_analyze.clicked.connect(self.analyzeStyle)
        self.btn_analyze.setEnabled(False)
        self.btn_analyze.setFixedHeight(40)

        # 添加样式输入按钮
        self.btn_style_replace = QPushButton('精准替换', self)
        self.btn_style_replace.clicked.connect(self.styleBasedReplace)
        self.btn_style_replace.setEnabled(False)
        self.btn_style_replace.setFixedHeight(40)

        self.btn_save = QPushButton('保存图片', self)
        self.btn_save.clicked.connect(self.saveImage)
        self.btn_save.setEnabled(False)
        self.btn_save.setFixedHeight(40)

        # 字体大小调整控件
        font_size_label = QLabel('字体大小:')
        self.font_size_spinbox = QSpinBox()
        self.font_size_spinbox.setRange(8, 200)  # 增加上限到200
        self.font_size_spinbox.setValue(14)
        self.font_size_spinbox.valueChanged.connect(self.updateFontSize)

        button_layout.addWidget(self.btn_load)
        button_layout.addWidget(self.btn_replace)
        button_layout.addWidget(self.btn_analyze)
        button_layout.addWidget(self.btn_style_replace)
        button_layout.addWidget(self.btn_save)
        button_layout.addStretch()
        button_layout.addWidget(font_size_label)
        button_layout.addWidget(self.font_size_spinbox)

        # 创建滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setAlignment(Qt.AlignCenter)
        
        # 创建自定义图像标签
        self.label = ImageLabel(self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setScaledContents(False)
        
        self.scroll_area.setWidget(self.label)

        # 添加到主布局
        main_layout.addLayout(button_layout)
        main_layout.addWidget(self.scroll_area)
        
        # 状态提示标签
        self.status_label = QLabel("提示：框选日期区域 → 分析样式 → 直接应用样式 → 开启实时预览")
        self.status_label.setStyleSheet("color: #7f8c8d; font-style: italic; padding: 5px;")
        self.status_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(self.status_label)

    def updateFontSize(self, value):
        self.font_size = value

    def loadImage(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getOpenFileName(self, "选择截图", "",
                                                  "图片文件 (*.png *.jpg *.jpeg)", options=options)
        if fileName:
            self.original_image = Image.open(fileName)
            self.modified_image = self.original_image.copy()
            self.displayImage()
            self.btn_replace.setEnabled(True)
            self.btn_analyze.setEnabled(True)
            self.btn_style_replace.setEnabled(True)
            self.selection_start = None
            self.selection_end = None

    def displayImage(self):
        if self.modified_image:
            img = self.modified_image.convert("RGBA")
            data = img.tobytes("raw", "RGBA")
            qim = QImage(data, img.size[0], img.size[1], QImage.Format_RGBA8888)
            pixmap = QPixmap.fromImage(qim)
            
            # 设置标签大小为图像的实际大小，但限制最大尺寸
            img_width, img_height = self.modified_image.size
            max_width = 1500
            max_height = 1200
            
            if img_width > max_width or img_height > max_height:
                # 按比例缩放
                scale = min(max_width / img_width, max_height / img_height)
                new_width = int(img_width * scale)
                new_height = int(img_height * scale)
                pixmap = pixmap.scaled(new_width, new_height, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                self.label.setFixedSize(new_width, new_height)
            else:
                self.label.setFixedSize(img_width, img_height)
            
            self.current_pixmap = pixmap
            self.label.setPixmap(pixmap)

    def drawSelection(self):
        if self.selection_start and self.selection_end and self.current_pixmap:
            # 创建一个新的pixmap来绘制选择框
            pixmap_with_selection = QPixmap(self.current_pixmap)
            painter = QPainter(pixmap_with_selection)
            
            # 设置画笔
            pen = QPen(Qt.red, 3, Qt.SolidLine)
            painter.setPen(pen)
            
            # 绘制选择框
            x1, y1 = self.selection_start
            x2, y2 = self.selection_end
            
            # 确保坐标在标签范围内
            label_width = self.label.width()
            label_height = self.label.height()
            
            x1 = max(0, min(x1, label_width))
            y1 = max(0, min(y1, label_height))
            x2 = max(0, min(x2, label_width))
            y2 = max(0, min(y2, label_height))
            
            rect = QRect(min(x1, x2), min(y1, y2), abs(x2 - x1), abs(y2 - y1))
            painter.drawRect(rect)
            painter.end()
            
            self.label.setPixmap(pixmap_with_selection)

    def analyze_text_color(self, image_region):
        """分析文本颜色，寻找最可能的文本颜色"""
        if image_region.size[0] == 0 or image_region.size[1] == 0:
            return (0, 0, 0)
            
        # 转换为灰度图像进行分析
        gray_img = image_region.convert('L')
        pixels = list(gray_img.getdata())
        
        # 创建直方图
        histogram = {}
        for pixel in pixels:
            histogram[pixel] = histogram.get(pixel, 0) + 1
        
        # 寻找最暗和最亮的颜色
        sorted_colors = sorted(histogram.keys())
        dark_threshold = sorted_colors[len(sorted_colors) // 4]  # 25%分位数
        
        # 如果有很暗的像素（可能是文字），返回深色
        dark_pixels = sum(count for color, count in histogram.items() if color < dark_threshold)
        total_pixels = len(pixels)
        
        if dark_pixels > total_pixels * 0.1:  # 如果超过10%是深色像素
            return (0, 0, 0)  # 返回黑色
        else:
            return (64, 64, 64)  # 返回深灰色

    def get_dominant_background_color(self, image_region):
        """获取主要背景色"""
        if image_region.size[0] == 0 or image_region.size[1] == 0:
            return (255, 255, 255)
            
        # 缩放图像以提高处理速度
        small_img = image_region.resize((50, 30))
        pixels = list(small_img.getdata())
        
        # 统计颜色出现频率
        color_count = {}
        for pixel in pixels:
            pixel = tuple(pixel[:3])  # 只取RGB，忽略Alpha
            color_count[pixel] = color_count.get(pixel, 0) + 1
        
        # 返回出现最频繁的颜色
        if color_count:
            return max(color_count.items(), key=lambda x: x[1])[0]
        return (255, 255, 255)

    def extract_date_from_region(self, image_region):
        """从选择区域提取日期信息（简化版OCR）"""
        # 这里是简化的实现，实际应用中可以集成Tesseract OCR
        # 根据您提供的示例，我们假设识别出的文本格式
        return "2025-06-25 00点至2025-06-25 17点"

    def replaceDate(self):
        if not (self.selection_start and self.selection_end):
            QMessageBox.warning(self, "警告", "请先框选要替换的日期区域")
            return

        # 获取用户输入的新日期
        new_date, ok = QInputDialog.getText(self, '输入新日期',
                                            '请输入要替换的新日期 (YYYY-MM-DD):',
                                            text=datetime.now().strftime('%Y-%m-%d'))
        if not ok or not new_date:
            return

        try:
            # 验证日期格式
            datetime.strptime(new_date, '%Y-%m-%d')
        except ValueError:
            QMessageBox.warning(self, "错误", "日期格式不正确，请使用YYYY-MM-DD格式")
            return

        # 计算实际选择的图像区域
        img_width, img_height = self.modified_image.size
        label_width = self.label.width()
        label_height = self.label.height()

        # 计算缩放比例
        if hasattr(self, 'current_pixmap'):
            scale_x = img_width / self.current_pixmap.width()
            scale_y = img_height / self.current_pixmap.height()
        else:
            scale_x = scale_y = 1

        x1 = int(self.selection_start[0] * scale_x)
        y1 = int(self.selection_start[1] * scale_y)
        x2 = int(self.selection_end[0] * scale_x)
        y2 = int(self.selection_end[1] * scale_y)

        # 确保坐标顺序正确
        x1, x2 = min(x1, x2), max(x1, x2)
        y1, y2 = min(y1, y2), max(y1, y2)

        # 确保坐标在图像范围内
        x1 = max(0, min(x1, img_width - 1))
        y1 = max(0, min(y1, img_height - 1))
        x2 = max(0, min(x2, img_width - 1))
        y2 = max(0, min(y2, img_height - 1))

        try:
            # 提取选择区域的图像
            selected_region = self.original_image.crop((x1, y1, x2, y2))

            # 提取原始文本
            original_text = self.extract_date_from_region(selected_region)

            # 智能生成新文本
            if "至" in original_text:
                parts = original_text.split("至")
                start_part = parts[0].strip()
                end_part = parts[1].strip()

                # 提取时间部分
                start_time = start_part.split()[-1] if " " in start_part else "00点"
                end_time = end_part.split()[-1] if " " in end_part else "17点"

                # 构建新文本
                new_text = f"{new_date} {start_time}至{new_date} {end_time}"
            else:
                new_text = new_date

            # 分析原始区域的颜色
            bg_color = self.get_dominant_background_color(selected_region)
            text_color = self.analyze_text_color(selected_region)

            # 绘制替换文本
            draw = ImageDraw.Draw(self.modified_image)

            # 尝试多种字体
            font = None
            font_paths = [
                "C:/Windows/Fonts/simhei.ttf",  # 黑体
                "C:/Windows/Fonts/msyh.ttc",    # 微软雅黑
                "C:/Windows/Fonts/simsun.ttc",  # 宋体
                "arial.ttf",
                None  # 默认字体
            ]
            
            for font_path in font_paths:
                try:
                    if font_path:
                        font = ImageFont.truetype(font_path, self.font_size)
                        break
                    else:
                        font = ImageFont.load_default()
                        break
                except:
                    continue

            if not font:
                font = ImageFont.load_default()

            # 获取文本尺寸
            bbox = draw.textbbox((0, 0), new_text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]

            # 计算文本位置
            region_width = x2 - x1
            region_height = y2 - y1
            
            # 如果文本太大，调整字体大小
            if text_width > region_width * 0.9 or text_height > region_height * 0.9:
                # 自动调整字体大小
                scale_factor = min(
                    (region_width * 0.9) / text_width,
                    (region_height * 0.9) / text_height
                )
                adjusted_font_size = max(8, int(self.font_size * scale_factor))
                
                for font_path in font_paths:
                    try:
                        if font_path:
                            font = ImageFont.truetype(font_path, adjusted_font_size)
                            break
                        else:
                            font = ImageFont.load_default()
                            break
                    except:
                        continue
                
                bbox = draw.textbbox((0, 0), new_text, font=font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]

            # 计算居中位置
            text_x = x1 + (region_width - text_width) // 2
            text_y = y1 + (region_height - text_height) // 2

            # 用背景色填充原区域（添加一些边距以完全覆盖原文）
            margin = 2
            draw.rectangle([x1-margin, y1-margin, x2+margin, y2+margin], fill=bg_color)

            # 绘制新文本
            draw.text((text_x, text_y), new_text, fill=text_color, font=font)

            self.displayImage()
            self.btn_save.setEnabled(True)
            QMessageBox.information(self, "成功", f"日期已替换完成\n新文本: {new_text}\n字体大小: {font.size if hasattr(font, 'size') else '默认'}")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"替换过程中发生错误: {str(e)}")

    def get_background_color(self, image_region):
        """获取区域背景色(保留原方法作为备用)"""
        return self.get_dominant_background_color(image_region)

    def get_text_color(self, image_region):
        """获取文本颜色(保留原方法作为备用)"""
        return self.analyze_text_color(image_region)

    def saveImage(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getSaveFileName(self, "保存图片", "",
                                                  "PNG图片 (*.png)", options=options)
        if fileName:
            if not fileName.lower().endswith('.png'):
                fileName += '.png'
            self.modified_image.save(fileName)
            QMessageBox.information(self, "成功", f"图片已保存到 {fileName}")

    def analyzeStyle(self):
        """分析框选区域的样式、格式和颜色风格"""
        if not (self.selection_start and self.selection_end):
            QMessageBox.warning(self, "警告", "请先框选要分析的区域")
            return

        try:
            # 计算实际选择的图像区域
            img_width, img_height = self.modified_image.size
            
            # 计算缩放比例
            if hasattr(self, 'current_pixmap'):
                scale_x = img_width / self.current_pixmap.width()
                scale_y = img_height / self.current_pixmap.height()
            else:
                scale_x = scale_y = 1

            x1 = int(self.selection_start[0] * scale_x)
            y1 = int(self.selection_start[1] * scale_y)
            x2 = int(self.selection_end[0] * scale_x)
            y2 = int(self.selection_end[1] * scale_y)

            # 确保坐标顺序正确
            x1, x2 = min(x1, x2), max(x1, x2)
            y1, y2 = min(y1, y2), max(y1, y2)

            # 确保坐标在图像范围内
            x1 = max(0, min(x1, img_width - 1))
            y1 = max(0, min(y1, img_height - 1))
            x2 = max(0, min(x2, img_width - 1))
            y2 = max(0, min(y2, img_height - 1))

            # 提取选择区域
            selected_region = self.original_image.crop((x1, y1, x2, y2))
            
            # 进行详细的样式分析
            analysis_result = self.perform_detailed_style_analysis(selected_region)
            
            # 显示分析结果
            self.show_style_analysis_result(analysis_result, (x2-x1, y2-y1))
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"样式分析过程中发生错误: {str(e)}")

    def perform_detailed_style_analysis(self, image_region):
        """执行详细的样式分析"""
        if image_region.size[0] == 0 or image_region.size[1] == 0:
            return None
            
        analysis = {}
        
        # 1. 基本信息
        analysis['dimensions'] = {
            'width': image_region.size[0],
            'height': image_region.size[1],
            'aspect_ratio': round(image_region.size[0] / image_region.size[1], 2)
        }
        
        # 2. 颜色分析
        analysis['colors'] = self.analyze_colors(image_region)
        
        # 3. 亮度和对比度分析
        analysis['brightness'] = self.analyze_brightness(image_region)
        
        # 4. 边缘和结构分析
        analysis['structure'] = self.analyze_structure(image_region)
        
        # 5. 文本特征分析
        analysis['text_features'] = self.analyze_text_features(image_region)
        
        return analysis

    def analyze_colors(self, image_region):
        """分析颜色特征"""
        # 转换为RGB模式
        rgb_img = image_region.convert('RGB')
        pixels = list(rgb_img.getdata())
        
        # 颜色统计
        color_count = {}
        for pixel in pixels:
            color_count[pixel] = color_count.get(pixel, 0) + 1
        
        # 获取主要颜色（前5种）
        sorted_colors = sorted(color_count.items(), key=lambda x: x[1], reverse=True)
        top_colors = sorted_colors[:5]
        
        # 计算主要颜色的占比
        total_pixels = len(pixels)
        main_colors = []
        for color, count in top_colors:
            percentage = round((count / total_pixels) * 100, 1)
            main_colors.append({
                'rgb': color,
                'hex': f"#{color[0]:02x}{color[1]:02x}{color[2]:02x}",
                'percentage': percentage
            })
        
        # 分析色调特征
        r_avg = sum(p[0] for p in pixels) / len(pixels)
        g_avg = sum(p[1] for p in pixels) / len(pixels)
        b_avg = sum(p[2] for p in pixels) / len(pixels)
        
        return {
            'main_colors': main_colors,
            'average_rgb': (int(r_avg), int(g_avg), int(b_avg)),
            'average_hex': f"#{int(r_avg):02x}{int(g_avg):02x}{int(b_avg):02x}",
            'color_diversity': len(color_count),  # 总颜色数量
            'is_monochromatic': len([c for c in main_colors if c['percentage'] > 50]) > 0
        }

    def analyze_brightness(self, image_region):
        """分析亮度和对比度"""
        gray_img = image_region.convert('L')
        pixels = list(gray_img.getdata())
        
        avg_brightness = sum(pixels) / len(pixels)
        min_brightness = min(pixels)
        max_brightness = max(pixels)
        contrast = max_brightness - min_brightness
        
        # 亮度分布
        dark_pixels = len([p for p in pixels if p < 85])
        medium_pixels = len([p for p in pixels if 85 <= p < 170])
        bright_pixels = len([p for p in pixels if p >= 170])
        
        return {
            'average': round(avg_brightness, 1),
            'min': min_brightness,
            'max': max_brightness,
            'contrast': contrast,
            'distribution': {
                'dark_ratio': round(dark_pixels / len(pixels) * 100, 1),
                'medium_ratio': round(medium_pixels / len(pixels) * 100, 1),
                'bright_ratio': round(bright_pixels / len(pixels) * 100, 1)
            },
            'brightness_level': 'dark' if avg_brightness < 85 else 'medium' if avg_brightness < 170 else 'bright'
        }

    def analyze_structure(self, image_region):
        """分析结构特征"""
        gray_img = image_region.convert('L')
        pixels = np.array(gray_img)
        
        # 边缘检测（简化版）
        if pixels.shape[0] > 1 and pixels.shape[1] > 1:
            # 计算梯度
            grad_x = np.abs(np.diff(pixels, axis=1))
            grad_y = np.abs(np.diff(pixels, axis=0))
            
            # 边缘强度
            edge_strength = np.mean(grad_x) + np.mean(grad_y)
            
            # 纹理复杂度（像素值变化的标准差）
            texture_complexity = np.std(pixels)
        else:
            edge_strength = 0
            texture_complexity = 0
        
        return {
            'edge_strength': round(edge_strength, 2),
            'texture_complexity': round(texture_complexity, 2),
            'structure_type': 'smooth' if texture_complexity < 20 else 'textured' if texture_complexity < 50 else 'complex'
        }

    def analyze_text_features(self, image_region):
        """分析可能的文本特征"""
        gray_img = image_region.convert('L')
        pixels = list(gray_img.getdata())
        
        if not pixels:
            return {
                'has_text_pattern': False,
                'estimated_font_size': 14,
                'text_background_contrast': 0,
                'likely_text_color': (0, 0, 0),
                'likely_background_color': (255, 255, 255)
            }
        
        # 文本特征分析
        # 1. 双峰分布检测（文本通常有明显的前景背景对比）
        histogram = {}
        for pixel in pixels:
            histogram[pixel] = histogram.get(pixel, 0) + 1
        
        # 寻找主要的亮度峰值
        sorted_brightness = sorted(histogram.items())
        peaks = []
        for i in range(1, len(sorted_brightness) - 1):
            brightness, count = sorted_brightness[i]
            prev_count = sorted_brightness[i-1][1]
            next_count = sorted_brightness[i+1][1]
            if count > prev_count and count > next_count and count > len(pixels) * 0.05:
                peaks.append((brightness, count))
        
        # 估计字体大小（基于区域高度）
        estimated_font_size = max(8, min(100, int(image_region.size[1] * 0.7)))
        
        # 更智能的文本和背景色分析
        min_brightness = min(pixels)
        max_brightness = max(pixels)
        avg_brightness = sum(pixels) / len(pixels)
        contrast = max_brightness - min_brightness
        
        # 根据亮度分布判断文本和背景
        dark_threshold = avg_brightness * 0.7
        bright_threshold = avg_brightness * 1.3
        
        dark_pixels = [p for p in pixels if p <= dark_threshold]
        bright_pixels = [p for p in pixels if p >= bright_threshold]
        
        # 判断哪个是文本，哪个是背景
        if len(dark_pixels) < len(bright_pixels):
            # 暗像素较少，可能是暗色文本在亮色背景上
            likely_text_brightness = sum(dark_pixels) / len(dark_pixels) if dark_pixels else min_brightness
            likely_bg_brightness = sum(bright_pixels) / len(bright_pixels) if bright_pixels else max_brightness
        else:
            # 亮像素较少，可能是亮色文本在暗色背景上
            likely_text_brightness = sum(bright_pixels) / len(bright_pixels) if bright_pixels else max_brightness
            likely_bg_brightness = sum(dark_pixels) / len(dark_pixels) if dark_pixels else min_brightness
        
        return {
            'has_text_pattern': len(peaks) >= 1 and contrast > 30,  # 降低双峰要求
            'estimated_font_size': estimated_font_size,
            'text_background_contrast': contrast,
            'likely_text_color': int(likely_text_brightness),
            'likely_background_color': int(likely_bg_brightness),
            'avg_brightness': avg_brightness,
            'dark_pixel_ratio': len(dark_pixels) / len(pixels) if pixels else 0,
            'bright_pixel_ratio': len(bright_pixels) / len(pixels) if pixels else 0
        }

    def show_style_analysis_result(self, analysis, region_size):
        """显示样式分析结果"""
        if not analysis:
            QMessageBox.warning(self, "警告", "无法分析选择的区域")
            return
            
        # 保存分析结果
        self.last_analysis_result = analysis
        
        # 构建详细的分析报告
        report = "=== 样式分析报告 ===\n\n"
        
        # 基本信息
        report += f"📐 区域尺寸: {analysis['dimensions']['width']} × {analysis['dimensions']['height']} 像素\n"
        report += f"📏 宽高比: {analysis['dimensions']['aspect_ratio']}\n\n"
        
        # 颜色信息
        report += "🎨 颜色分析:\n"
        report += f"• 主要颜色 (前3种):\n"
        for i, color in enumerate(analysis['colors']['main_colors'][:3]):
            report += f"  {i+1}. RGB{color['rgb']} | {color['hex']} | {color['percentage']}%\n"
        report += f"• 平均颜色: RGB{analysis['colors']['average_rgb']} | {analysis['colors']['average_hex']}\n"
        report += f"• 颜色丰富度: {analysis['colors']['color_diversity']} 种颜色\n"
        report += f"• 单色系: {'是' if analysis['colors']['is_monochromatic'] else '否'}\n\n"
        
        # 亮度信息
        report += "💡 亮度分析:\n"
        report += f"• 平均亮度: {analysis['brightness']['average']}/255 ({analysis['brightness']['brightness_level']})\n"
        report += f"• 对比度: {analysis['brightness']['contrast']}\n"
        report += f"• 亮度分布: 暗{analysis['brightness']['distribution']['dark_ratio']}% | "
        report += f"中{analysis['brightness']['distribution']['medium_ratio']}% | "
        report += f"亮{analysis['brightness']['distribution']['bright_ratio']}%\n\n"
        
        # 结构信息
        report += "🔧 结构分析:\n"
        report += f"• 边缘强度: {analysis['structure']['edge_strength']}\n"
        report += f"• 纹理复杂度: {analysis['structure']['texture_complexity']}\n"
        report += f"• 结构类型: {analysis['structure']['structure_type']}\n\n"
        
        # 文本特征
        report += "📝 文本特征:\n"
        report += f"• 疑似包含文本: {'是' if analysis['text_features']['has_text_pattern'] else '否'}\n"
        report += f"• 建议字体大小: {analysis['text_features']['estimated_font_size']}px\n"
        report += f"• 文本背景对比度: {analysis['text_features']['text_background_contrast']}\n"
        
        # 建议的替换参数
        report += "\n=== 伪装建议 ===\n"
        bg_color = analysis['colors']['main_colors'][0]['rgb']
        report += f"• 建议背景色: RGB{bg_color} | {analysis['colors']['main_colors'][0]['hex']}\n"
        report += f"• 建议文字颜色: {analysis['text_features']['likely_text_color']}\n"
        report += f"• 建议字体大小: {analysis['text_features']['estimated_font_size']}px\n"
        
        # 更新字体大小建议到界面
        self.font_size_spinbox.setValue(analysis['text_features']['estimated_font_size'])
        
        # 创建自定义消息框，包含"直接应用"按钮
        msg = QMessageBox(self)
        msg.setWindowTitle("样式分析结果")
        msg.setText("样式分析完成！")
        msg.setDetailedText(report)
        
        # 添加自定义按钮
        apply_button = msg.addButton("直接应用样式", QMessageBox.ActionRole)
        copy_button = msg.addButton("复制报告", QMessageBox.ActionRole)
        close_button = msg.addButton("关闭", QMessageBox.RejectRole)
        
        msg.exec_()
        
        # 处理按钮点击
        if msg.clickedButton() == apply_button:
            self.apply_analyzed_style()
        elif msg.clickedButton() == copy_button:
            # 复制报告到剪贴板
            clipboard = QApplication.clipboard()
            clipboard.setText(report)
            QMessageBox.information(self, "已复制", "样式分析报告已复制到剪贴板")

    def styleBasedReplace(self):
        """基于样式参数的精准替换"""
        if not (self.selection_start and self.selection_end):
            QMessageBox.warning(self, "警告", "请先框选要替换的日期区域")
            return

        # 打开样式输入对话框
        style_dialog = StyleInputDialog(self)
        if style_dialog.exec_() == QDialog.Accepted:
            style_params = style_dialog.get_style_params()
            
            # 获取用户输入的新日期
            new_date, ok = QInputDialog.getText(self, '输入新日期',
                                                '请输入要替换的新日期 (YYYY-MM-DD):',
                                                text=datetime.now().strftime('%Y-%m-%d'))
            if not ok or not new_date:
                return

            try:
                # 验证日期格式
                datetime.strptime(new_date, '%Y-%m-%d')
            except ValueError:
                QMessageBox.warning(self, "错误", "日期格式不正确，请使用YYYY-MM-DD格式")
                return

            self.perform_precise_replacement(new_date, style_params)

    def perform_precise_replacement(self, new_date, style_params):
        """执行精准替换"""
        try:
            # 计算实际选择的图像区域
            img_width, img_height = self.modified_image.size
            
            # 计算缩放比例
            if hasattr(self, 'current_pixmap'):
                scale_x = img_width / self.current_pixmap.width()
                scale_y = img_height / self.current_pixmap.height()
            else:
                scale_x = scale_y = 1

            x1 = int(self.selection_start[0] * scale_x)
            y1 = int(self.selection_start[1] * scale_y)
            x2 = int(self.selection_end[0] * scale_x)
            y2 = int(self.selection_end[1] * scale_y)

            # 确保坐标顺序正确
            x1, x2 = min(x1, x2), max(x1, x2)
            y1, y2 = min(y1, y2), max(y1, y2)

            # 确保坐标在图像范围内
            x1 = max(0, min(x1, img_width - 1))
            y1 = max(0, min(y1, img_height - 1))
            x2 = max(0, min(x2, img_width - 1))
            y2 = max(0, min(y2, img_height - 1))

            # 提取选择区域进行分析
            selected_region = self.original_image.crop((x1, y1, x2, y2))

            # 智能生成新文本（保持原有逻辑）
            original_text = self.extract_date_from_region(selected_region)
            if "至" in original_text:
                parts = original_text.split("至")
                start_part = parts[0].strip()
                end_part = parts[1].strip()

                # 提取时间部分
                start_time = start_part.split()[-1] if " " in start_part else "00点"
                end_time = end_part.split()[-1] if " " in end_part else "17点"

                # 构建新文本
                new_text = f"{new_date} {start_time}至{new_date} {end_time}"
            else:
                new_text = new_date

            # 使用样式参数进行精准替换
            draw = ImageDraw.Draw(self.modified_image)

            # 使用指定的字体大小
            font = self.get_best_font(style_params['font_size'])

            # 计算精确的文本尺寸
            bbox = draw.textbbox((0, 0), new_text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]

            # 使用样式参数中的区域尺寸来调整位置
            target_width = style_params['width']
            target_height = style_params['height']
            
            # 如果选择区域与目标尺寸差异很大，按比例调整
            region_width = x2 - x1
            region_height = y2 - y1
            
            if abs(region_width - target_width) > 50 or abs(region_height - target_height) > 10:
                # 使用实际选择区域的尺寸，但参考目标比例
                scale_factor = min(region_width / target_width, region_height / target_height)
                adjusted_font_size = max(8, int(style_params['font_size'] * scale_factor))
                font = self.get_best_font(adjusted_font_size)
                
                bbox = draw.textbbox((0, 0), new_text, font=font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]

            # 精确定位文本位置（考虑样式参数）
            if text_width > region_width * 0.95:
                # 文本太宽，缩小字体
                scale_factor = (region_width * 0.9) / text_width
                adjusted_font_size = max(8, int(style_params['font_size'] * scale_factor))
                font = self.get_best_font(adjusted_font_size)
                
                bbox = draw.textbbox((0, 0), new_text, font=font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]

            # 计算居中位置
            text_x = x1 + (region_width - text_width) // 2
            text_y = y1 + (region_height - text_height) // 2

            # 使用样式参数的颜色
            bg_color = style_params['bg_color']
            text_color = style_params['text_color']

            # 清除原区域（使用指定的背景色）
            margin = 3  # 稍微扩大清除范围
            draw.rectangle([x1-margin, y1-margin, x2+margin, y2+margin], fill=bg_color)

            # 绘制新文本（使用精确的样式参数）
            draw.text((text_x, text_y), new_text, fill=text_color, font=font)

            # 如果需要增强对比度
            if style_params['contrast'] > 150:
                # 添加轻微的阴影效果来增强对比度
                shadow_color = tuple(max(0, c-30) for c in text_color) if sum(text_color) > 384 else tuple(min(255, c+30) for c in text_color)
                draw.text((text_x+1, text_y+1), new_text, fill=shadow_color, font=font)
                draw.text((text_x, text_y), new_text, fill=text_color, font=font)

            self.displayImage()
            self.btn_save.setEnabled(True)
            
            # 显示替换详情
            details = f"""精准替换完成！

新文本: {new_text}
使用的样式参数:
• 背景色: RGB{bg_color}
• 文字色: RGB{text_color}
• 字体大小: {font.size if hasattr(font, 'size') else style_params['font_size']}px
• 位置: ({text_x}, {text_y})
• 区域: {region_width}×{region_height}px"""
            
            QMessageBox.information(self, "精准替换完成", details)

        except Exception as e:
            QMessageBox.critical(self, "错误", f"精准替换过程中发生错误: {str(e)}")

    def get_best_font(self, font_size):
        """获取最佳字体"""
        font_paths = [
            "C:/Windows/Fonts/simhei.ttf",    # 黑体
            "C:/Windows/Fonts/msyh.ttc",      # 微软雅黑
            "C:/Windows/Fonts/simsun.ttc",    # 宋体
            "arial.ttf",
        ]
        
        for font_path in font_paths:
            try:
                return ImageFont.truetype(font_path, font_size)
            except:
                continue
        
        # 如果都失败了，使用默认字体
        return ImageFont.load_default()

    def apply_analyzed_style(self):
        """直接应用分析出的样式进行替换"""
        if not self.last_analysis_result:
            QMessageBox.warning(self, "警告", "没有可用的样式分析结果，请先分析样式")
            return
            
        if not (self.selection_start and self.selection_end):
            QMessageBox.warning(self, "警告", "请先框选要替换的日期区域")
            return
        
        # 将分析结果转换为样式参数
        initial_style_params = self.convert_analysis_to_style_params(self.last_analysis_result)
        
        # 打开样式微调对话框
        adjustment_dialog = StyleAdjustmentDialog(initial_style_params, self)
        if adjustment_dialog.exec_() == QDialog.Accepted:
            adjusted_params = adjustment_dialog.get_adjusted_params()
            
            # 获取预览模式下的最终位置（如果有的话）
            final_position = None
            if self.label.preview_mode and self.label.preview_position:
                final_position = self.label.preview_position
            
            # 退出预览模式
            self.exit_preview_mode()
            
            # 获取用户输入的新日期
            new_date, ok = QInputDialog.getText(self, '输入新日期',
                                                '请输入要替换的新日期 (YYYY-MM-DD):',
                                                text=datetime.now().strftime('%Y-%m-%d'))
            if not ok or not new_date:
                return

            try:
                # 验证日期格式
                datetime.strptime(new_date, '%Y-%m-%d')
            except ValueError:
                QMessageBox.warning(self, "错误", "日期格式不正确，请使用YYYY-MM-DD格式")
                return

            # 执行精准替换，传入最终位置
            self.perform_precise_replacement_with_adjustments(new_date, adjusted_params, final_position)

    def convert_analysis_to_style_params(self, analysis):
        """将分析结果转换为样式参数格式"""
        # 获取主要背景色（通常是最常见的颜色）
        bg_color = analysis['colors']['main_colors'][0]['rgb']
        
        # 智能选择文本颜色
        text_color = self.smart_text_color_selection(analysis)
        
        # 如果文本颜色和背景颜色太相似，调整对比度
        text_color = self.ensure_contrast(bg_color, text_color)
        
        return {
            'bg_color': bg_color,
            'text_color': text_color,
            'font_size': analysis['text_features']['estimated_font_size'],
            'width': analysis['dimensions']['width'],
            'height': analysis['dimensions']['height'],
            'brightness_level': analysis['brightness']['brightness_level'],
            'contrast': analysis['brightness']['contrast']
        }
    
    def smart_text_color_selection(self, analysis):
        """智能选择文本颜色"""
        # 获取分析出的可能文本颜色
        likely_text_brightness = analysis['text_features']['likely_text_color']
        bg_color = analysis['colors']['main_colors'][0]['rgb']
        bg_brightness = sum(bg_color) / 3
        
        # 策略1: 使用分析出的文本亮度值
        if isinstance(likely_text_brightness, (int, float)):
            text_color = (int(likely_text_brightness), int(likely_text_brightness), int(likely_text_brightness))
        else:
            text_color = likely_text_brightness
        
        # 策略2: 从主要颜色中选择与背景对比度最大的颜色
        max_contrast = 0
        best_text_color = text_color
        
        for color_info in analysis['colors']['main_colors'][:5]:  # 检查前5种颜色
            color = color_info['rgb']
            color_brightness = sum(color) / 3
            contrast = abs(bg_brightness - color_brightness)
            
            # 如果这个颜色与背景有更好的对比度，并且不是背景色本身
            if (contrast > max_contrast and contrast > 50 and 
                color != bg_color and color_info['percentage'] < 80):  # 不是主导色
                max_contrast = contrast
                best_text_color = color
        
        # 策略3: 如果仍然没有好的对比度，使用经典的黑白对比
        final_contrast = abs(sum(best_text_color)/3 - bg_brightness)
        if final_contrast < 80:  # 对比度不够
            if bg_brightness > 150:  # 浅色背景
                best_text_color = (0, 0, 0)  # 黑色文本
            else:  # 深色背景
                best_text_color = (255, 255, 255)  # 白色文本
        
        return best_text_color
    
    def ensure_contrast(self, bg_color, text_color, min_contrast=100):
        """确保文本和背景有足够的对比度"""
        bg_brightness = sum(bg_color) / 3
        text_brightness = sum(text_color) / 3
        contrast = abs(bg_brightness - text_brightness)
        
        if contrast < min_contrast:
            # 对比度不够，调整文本颜色
            if bg_brightness > 127:  # 浅色背景
                # 使文本更暗
                factor = max(0.3, (min_contrast - contrast) / 255)
                text_color = tuple(max(0, int(c * (1 - factor))) for c in text_color)
            else:  # 深色背景
                # 使文本更亮
                factor = max(0.3, (min_contrast - contrast) / 255)
                text_color = tuple(min(255, int(c + (255 - c) * factor)) for c in text_color)
        
        return text_color

    def perform_precise_replacement_with_adjustments(self, new_date, adjusted_params, final_position):
        """执行带有微调参数的精准替换"""
        try:
            # 计算实际选择的图像区域
            img_width, img_height = self.modified_image.size
            
            # 计算缩放比例
            if hasattr(self, 'current_pixmap'):
                scale_x = img_width / self.current_pixmap.width()
                scale_y = img_height / self.current_pixmap.height()
            else:
                scale_x = scale_y = 1

            x1 = int(self.selection_start[0] * scale_x)
            y1 = int(self.selection_start[1] * scale_y)
            x2 = int(self.selection_end[0] * scale_x)
            y2 = int(self.selection_end[1] * scale_y)

            # 确保坐标顺序正确
            x1, x2 = min(x1, x2), max(x1, x2)
            y1, y2 = min(y1, y2), max(y1, y2)

            # 确保坐标在图像范围内
            x1 = max(0, min(x1, img_width - 1))
            y1 = max(0, min(y1, img_height - 1))
            x2 = max(0, min(x2, img_width - 1))
            y2 = max(0, min(y2, img_height - 1))

            # 提取选择区域进行分析
            selected_region = self.original_image.crop((x1, y1, x2, y2))

            # 智能生成新文本（保持原有逻辑）
            original_text = self.extract_date_from_region(selected_region)
            if "至" in original_text:
                parts = original_text.split("至")
                start_part = parts[0].strip()
                end_part = parts[1].strip()

                # 提取时间部分
                start_time = start_part.split()[-1] if " " in start_part else "00点"
                end_time = end_part.split()[-1] if " " in end_part else "17点"

                # 构建新文本
                new_text = f"{new_date} {start_time}至{new_date} {end_time}"
            else:
                new_text = new_date

            # 使用微调后的样式参数进行替换
            draw = ImageDraw.Draw(self.modified_image)

            # 获取带字体粗细的字体
            font = self.get_font_with_weight(adjusted_params['font_size'], adjusted_params['font_weight'])

            # 计算精确的文本尺寸
            bbox = draw.textbbox((0, 0), new_text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
            
            # 处理大字体的特殊情况
            if hasattr(font, 'requested_size') and font.requested_size > 40:
                # 对于大字体，计算缩放比例
                scale_factor = font.requested_size / 40  # 以40为基准
                text_width = int(text_width * scale_factor)
                text_height = int(text_height * scale_factor)

            # 计算区域尺寸
            region_width = x2 - x1
            region_height = y2 - y1
            
            # 如果文本太大，自动调整字体大小
            if text_width > region_width * 0.95 or text_height > region_height * 0.95:
                scale_factor = min(
                    (region_width * 0.9) / text_width,
                    (region_height * 0.9) / text_height
                )
                adjusted_font_size = max(8, int(adjusted_params['font_size'] * scale_factor))
                font = self.get_font_with_weight(adjusted_font_size, adjusted_params['font_weight'])
                
                bbox = draw.textbbox((0, 0), new_text, font=font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]
                
                # 重新处理大字体
                if hasattr(font, 'requested_size') and font.requested_size > 40:
                    scale_factor = font.requested_size / 40
                    text_width = int(text_width * scale_factor)
                    text_height = int(text_height * scale_factor)

            # 计算文本位置（包含位置偏移）
            text_x = x1 + (region_width - text_width) // 2 + adjusted_params['x_offset']
            text_y = y1 + (region_height - text_height) // 2 + adjusted_params['y_offset']

            # 如果有最终拖拽位置，使用拖拽位置
            if final_position:
                # 将屏幕坐标转换为图像坐标
                if hasattr(self, 'current_pixmap'):
                    scale_x = img_width / self.current_pixmap.width()
                    scale_y = img_height / self.current_pixmap.height()
                    
                    final_x = int(final_position[0] * scale_x)
                    final_y = int(final_position[1] * scale_y)
                    
                    # 调整位置使文本居中
                    text_x = final_x - text_width // 2 + adjusted_params['x_offset']
                    text_y = final_y - text_height // 2 + adjusted_params['y_offset']

            # 使用微调后的颜色
            bg_color = adjusted_params['bg_color']
            text_color = adjusted_params['text_color']

            # 清除原区域（使用指定的背景色）
            margin = 3
            draw.rectangle([x1-margin, y1-margin, x2+margin, y2+margin], fill=bg_color)

            # 绘制阴影效果（如果启用）
            if adjusted_params['enable_shadow']:
                shadow_offset = adjusted_params['shadow_offset']
                shadow_color = self.calculate_shadow_color(text_color, bg_color)
                self.draw_text_with_size_support(draw, text_x + shadow_offset, text_y + shadow_offset, new_text, font, shadow_color)

            # 绘制主文本
            self.draw_text_with_size_support(draw, text_x, text_y, new_text, font, text_color)

            # 如果启用对比度增强
            if adjusted_params['enable_contrast']:
                # 绘制轻微的边缘效果
                edge_color = self.calculate_edge_color(text_color, bg_color)
                for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    self.draw_text_with_size_support(draw, text_x + dx, text_y + dy, new_text, font, edge_color)
                # 重新绘制主文本
                self.draw_text_with_size_support(draw, text_x, text_y, new_text, font, text_color)

            self.displayImage()
            self.btn_save.setEnabled(True)
            
            # 显示替换详情
            font_weight_names = ["细体", "正常", "半粗", "粗体", "超粗"]
            weight_name = font_weight_names[adjusted_params['font_weight']]
            
            details = f"""精准微调替换完成！

新文本: {new_text}
使用的样式参数:
• 背景色: RGB{bg_color}
• 文字色: RGB{text_color}
• 字体大小: {adjusted_params['font_size']}px
• 字体粗细: {weight_name}
• 位置: ({text_x}, {text_y})
• 位置偏移: ({adjusted_params['x_offset']}, {adjusted_params['y_offset']})
• 区域: {region_width}×{region_height}px
• 阴影效果: {'启用' if adjusted_params['enable_shadow'] else '禁用'}
• 对比度增强: {'启用' if adjusted_params['enable_contrast'] else '禁用'}"""
            
            QMessageBox.information(self, "精准微调替换完成", details)

        except Exception as e:
            QMessageBox.critical(self, "错误", f"精准替换过程中发生错误: {str(e)}")

    def get_font_with_weight(self, font_size, font_weight):
        """获取指定粗细的字体"""
        # 确保字体大小在合理范围内，并处理PIL的字体大小限制
        actual_font_size = max(8, min(200, font_size))  # 增加上限到200
        
        # 字体路径映射，按粗细程度排序
        font_paths_by_weight = [
            # 细体
            ["C:/Windows/Fonts/msyhl.ttc", "C:/Windows/Fonts/simsun.ttc"],
            # 正常
            ["C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/simhei.ttf", "C:/Windows/Fonts/simsun.ttc"],
            # 半粗
            ["C:/Windows/Fonts/msyhbd.ttc", "C:/Windows/Fonts/simhei.ttf"],
            # 粗体
            ["C:/Windows/Fonts/msyhbd.ttc", "C:/Windows/Fonts/simhei.ttf"],
            # 超粗
            ["C:/Windows/Fonts/msyhbd.ttc", "C:/Windows/Fonts/simhei.ttf"]
        ]
        
        # 根据字体粗细选择合适的字体文件
        font_paths = font_paths_by_weight[min(font_weight, 4)]
        
        # 尝试多种字体大小策略
        for font_path in font_paths:
            try:
                # 首先尝试直接使用指定大小
                font = ImageFont.truetype(font_path, actual_font_size)
                # 验证字体是否正确加载
                test_bbox = ImageDraw.Draw(Image.new('RGB', (100, 100))).textbbox((0, 0), "Test", font=font)
                test_height = test_bbox[3] - test_bbox[1]
                # 如果字体高度合理，返回这个字体
                if test_height > actual_font_size * 0.5:  # 确保字体确实按预期大小显示
                    return font
            except Exception as e:
                print(f"尝试字体 {font_path} 大小 {actual_font_size} 失败: {e}")
                continue
        
        # 如果标准方法失败，尝试系统默认字体
        try:
            # Windows系统字体
            default_fonts = [
                "C:/Windows/Fonts/arial.ttf",
                "C:/Windows/Fonts/calibri.ttf",
                "C:/Windows/Fonts/tahoma.ttf"
            ]
            
            for font_path in default_fonts:
                try:
                    return ImageFont.truetype(font_path, actual_font_size)
                except:
                    continue
        except:
            pass
        
        # 最后的备选方案：使用PIL的默认字体，但尝试模拟大字体效果
        try:
            # 对于很大的字体，我们使用默认字体的最大可用大小
            if actual_font_size > 40:
                default_font = ImageFont.load_default()
                # 将大字体信息保存到字体对象中，供后续处理使用
                default_font.requested_size = actual_font_size
                return default_font
            else:
                return ImageFont.load_default()
        except:
            # 创建一个虚拟字体对象
            class VirtualFont:
                def __init__(self, size):
                    self.size = size
                    self.requested_size = size
            return VirtualFont(actual_font_size)

    def calculate_shadow_color(self, text_color, bg_color):
        """计算阴影颜色"""
        # 阴影颜色通常比文本颜色更深，但要考虑背景色
        text_brightness = sum(text_color) / 3
        bg_brightness = sum(bg_color) / 3
        
        if text_brightness > bg_brightness:  # 亮色文本在暗色背景
            # 阴影使用更暗的颜色
            return tuple(max(0, c - 50) for c in text_color)
        else:  # 暗色文本在亮色背景
            # 阴影使用稍微浅一点的颜色
            return tuple(min(255, c + 30) for c in text_color)

    def calculate_edge_color(self, text_color, bg_color):
        """计算边缘增强颜色"""
        # 边缘颜色介于文本色和背景色之间
        return tuple(int((t + b) / 2) for t, b in zip(text_color, bg_color))

    def start_live_preview(self, preview_text, params):
        """启动实时预览模式"""
        self.label.set_preview_mode(True, preview_text, params)
        self.update_preview_display()
        self.status_label.setText("🎯 实时预览模式：拖拽红色文本到理想位置，调整参数后点击'确认应用'")
        self.status_label.setStyleSheet("color: #e74c3c; font-weight: bold; padding: 5px;")
        
    def update_live_preview(self, preview_text, params):
        """更新实时预览参数"""
        if self.label.preview_mode:
            self.label.preview_text = preview_text
            self.label.preview_params = params
            self.update_preview_display()
            
    def update_preview_display(self):
        """更新预览显示"""
        if not self.label.preview_mode or not self.label.preview_params:
            return
            
        # 创建一个新的pixmap来绘制预览
        if hasattr(self, 'current_pixmap'):
            preview_pixmap = QPixmap(self.current_pixmap)
            painter = QPainter(preview_pixmap)
            
            # 设置字体
            font = QFont()
            font.setPointSize(max(8, self.label.preview_params['font_size']))
            
            # 字体粗细映射
            weight_map = [QFont.Light, QFont.Normal, QFont.DemiBold, QFont.Bold, QFont.Black]
            font_weight = weight_map[min(self.label.preview_params.get('font_weight', 1), 4)]
            font.setWeight(font_weight)
            
            painter.setFont(font)
            
            # 设置颜色
            text_color = self.label.preview_params['text_color']
            bg_color = self.label.preview_params['bg_color']
            
            # 绘制背景矩形（半透明）
            if self.label.preview_position:
                x, y = self.label.preview_position
                
                # 计算文本尺寸
                font_metrics = painter.fontMetrics()
                text_rect = font_metrics.boundingRect(self.label.preview_text)
                text_width = text_rect.width()
                text_height = text_rect.height()
                
                # 添加内边距
                padding = 5
                bg_rect = QRect(
                    x - text_width//2 - padding,
                    y - text_height//2 - padding,
                    text_width + padding*2,
                    text_height + padding*2
                )
                
                # 绘制半透明背景
                painter.fillRect(bg_rect, QColor(bg_color[0], bg_color[1], bg_color[2], 200))
                
                # 绘制阴影（如果启用）
                if self.label.preview_params.get('enable_shadow', False):
                    shadow_offset = self.label.preview_params.get('shadow_offset', 1)
                    shadow_color = self.calculate_shadow_color(text_color, bg_color)
                    painter.setPen(QColor(shadow_color[0], shadow_color[1], shadow_color[2]))
                    painter.drawText(x - text_width//2 + shadow_offset, y + text_height//4 + shadow_offset, self.label.preview_text)
                
                # 绘制主文本
                painter.setPen(QColor(text_color[0], text_color[1], text_color[2]))
                painter.drawText(x - text_width//2, y + text_height//4, self.label.preview_text)
                
                # 绘制拖拽指示器
                painter.setPen(QPen(Qt.red, 2, Qt.DashLine))
                painter.drawRect(bg_rect)
                
                # 绘制拖拽图标
                painter.setPen(QPen(Qt.red, 2))
                icon_size = 8
                painter.drawLine(x-icon_size, y, x+icon_size, y)
                painter.drawLine(x, y-icon_size, x, y+icon_size)
            
            painter.end()
            self.label.setPixmap(preview_pixmap)
            
    def exit_preview_mode(self):
        """退出预览模式"""
        self.label.set_preview_mode(False)
        # 恢复原始显示
        self.displayImage()
        self.status_label.setText("提示：框选日期区域 → 分析样式 → 直接应用样式 → 开启实时预览")
        self.status_label.setStyleSheet("color: #7f8c8d; font-style: italic; padding: 5px;")

    def draw_text_with_size_support(self, draw, x, y, text, font, color):
        """支持大字体的文本绘制方法"""
        try:
            # 检查是否是特殊的大字体情况
            if hasattr(font, 'requested_size') and font.requested_size > 40:
                # 对于大字体，使用图像缩放技术
                scale_factor = font.requested_size / 40
                
                # 创建一个临时的高分辨率图像来绘制文本
                temp_width = int(len(text) * font.requested_size * 1.2)
                temp_height = int(font.requested_size * 1.5)
                
                # 使用最大可用的字体大小
                actual_font = None
                for size in [40, 36, 32, 28, 24, 20]:
                    try:
                        actual_font = ImageFont.truetype("C:/Windows/Fonts/msyh.ttc", size)
                        break
                    except:
                        continue
                
                if actual_font is None:
                    actual_font = ImageFont.load_default()
                
                # 在临时图像上绘制文本
                temp_img = Image.new('RGBA', (temp_width, temp_height), (0, 0, 0, 0))
                temp_draw = ImageDraw.Draw(temp_img)
                temp_draw.text((0, 0), text, fill=color, font=actual_font)
                
                # 缩放临时图像
                target_width = int(temp_width * scale_factor)
                target_height = int(temp_height * scale_factor)
                scaled_img = temp_img.resize((target_width, target_height), Image.LANCZOS)
                
                # 将缩放后的文本粘贴到主图像上
                # 获取主图像
                main_img = draw.im if hasattr(draw, 'im') else self.modified_image
                
                # 计算粘贴位置
                paste_x = max(0, int(x))
                paste_y = max(0, int(y))
                
                # 确保不超出图像边界
                if paste_x + target_width > main_img.size[0]:
                    target_width = main_img.size[0] - paste_x
                if paste_y + target_height > main_img.size[1]:
                    target_height = main_img.size[1] - paste_y
                
                if target_width > 0 and target_height > 0:
                    # 重新调整大小以适应边界
                    if target_width != scaled_img.size[0] or target_height != scaled_img.size[1]:
                        scaled_img = scaled_img.resize((target_width, target_height), Image.LANCZOS)
                    
                    # 粘贴文本（使用alpha通道）
                    main_img.paste(scaled_img, (paste_x, paste_y), scaled_img)
                
            else:
                # 标准字体大小，直接绘制
                draw.text((x, y), text, fill=color, font=font)
                
        except Exception as e:
            print(f"绘制文本时出错: {e}")
            # 降级到标准绘制方法
            try:
                draw.text((x, y), text, fill=color, font=font)
            except:
                # 最后的降级方案
                default_font = ImageFont.load_default()
                draw.text((x, y), text, fill=color, font=default_font)


class StyleAdjustmentDialog(QDialog):
    def __init__(self, style_params, parent=None):
        super().__init__(parent)
        self.setWindowTitle("样式微调")
        self.setFixedSize(400, 500)
        self.style_params = style_params.copy()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout(self)
        
        # 说明标签
        instruction = QLabel("基于分析结果，您可以微调以下样式参数：")
        instruction.setStyleSheet("font-weight: bold; color: #2c3e50; margin-bottom: 10px;")
        layout.addWidget(instruction)
        
        # 创建样式参数调整组
        params_group = QGroupBox("样式参数调整")
        params_layout = QFormLayout(params_group)
        
        # 字体大小调整
        font_size_layout = QHBoxLayout()
        self.font_size_spinbox = QSpinBox()
        self.font_size_spinbox.setRange(8, 200)  # 增加上限到200
        self.font_size_spinbox.setValue(self.style_params['font_size'])
        self.font_size_spinbox.setSuffix(" px")
        
        font_size_slider = QSlider(Qt.Horizontal)
        font_size_slider.setRange(8, 200)  # 增加上限到200
        font_size_slider.setValue(self.style_params['font_size'])
        font_size_slider.valueChanged.connect(self.font_size_spinbox.setValue)
        self.font_size_spinbox.valueChanged.connect(font_size_slider.setValue)
        
        font_size_layout.addWidget(self.font_size_spinbox)
        font_size_layout.addWidget(font_size_slider)
        params_layout.addRow("字体大小:", font_size_layout)
        
        # 字体粗细程度
        self.font_weight_combo = QComboBox()
        self.font_weight_combo.addItems([
            "细体 (Light)", 
            "正常 (Normal)", 
            "半粗 (Semi-Bold)", 
            "粗体 (Bold)", 
            "超粗 (Extra-Bold)"
        ])
        self.font_weight_combo.setCurrentIndex(1)  # 默认正常
        params_layout.addRow("字体粗细:", self.font_weight_combo)
        
        # 背景颜色微调
        bg_color_layout = QHBoxLayout()
        self.bg_r_spinbox = QSpinBox()
        self.bg_g_spinbox = QSpinBox()
        self.bg_b_spinbox = QSpinBox()
        
        for spinbox in [self.bg_r_spinbox, self.bg_g_spinbox, self.bg_b_spinbox]:
            spinbox.setRange(0, 255)
            spinbox.setFixedWidth(60)
        
        self.bg_r_spinbox.setValue(self.style_params['bg_color'][0])
        self.bg_g_spinbox.setValue(self.style_params['bg_color'][1])
        self.bg_b_spinbox.setValue(self.style_params['bg_color'][2])
        
        bg_color_layout.addWidget(QLabel("R:"))
        bg_color_layout.addWidget(self.bg_r_spinbox)
        bg_color_layout.addWidget(QLabel("G:"))
        bg_color_layout.addWidget(self.bg_g_spinbox)
        bg_color_layout.addWidget(QLabel("B:"))
        bg_color_layout.addWidget(self.bg_b_spinbox)
        
        self.bg_preview = QLabel()
        self.bg_preview.setFixedSize(30, 20)
        self.bg_preview.setStyleSheet(f"background-color: rgb{self.style_params['bg_color']}; border: 1px solid #ccc;")
        bg_color_layout.addWidget(self.bg_preview)
        bg_color_layout.addStretch()
        
        params_layout.addRow("背景颜色:", bg_color_layout)
        
        # 文字颜色微调
        text_color_layout = QHBoxLayout()
        self.text_r_spinbox = QSpinBox()
        self.text_g_spinbox = QSpinBox()
        self.text_b_spinbox = QSpinBox()
        
        for spinbox in [self.text_r_spinbox, self.text_g_spinbox, self.text_b_spinbox]:
            spinbox.setRange(0, 255)
            spinbox.setFixedWidth(60)
        
        self.text_r_spinbox.setValue(self.style_params['text_color'][0])
        self.text_g_spinbox.setValue(self.style_params['text_color'][1])
        self.text_b_spinbox.setValue(self.style_params['text_color'][2])
        
        text_color_layout.addWidget(QLabel("R:"))
        text_color_layout.addWidget(self.text_r_spinbox)
        text_color_layout.addWidget(QLabel("G:"))
        text_color_layout.addWidget(self.text_g_spinbox)
        text_color_layout.addWidget(QLabel("B:"))
        text_color_layout.addWidget(self.text_b_spinbox)
        
        self.text_preview = QLabel()
        self.text_preview.setFixedSize(30, 20)
        self.text_preview.setStyleSheet(f"background-color: rgb{self.style_params['text_color']}; border: 1px solid #ccc;")
        text_color_layout.addWidget(self.text_preview)
        text_color_layout.addStretch()
        
        params_layout.addRow("文字颜色:", text_color_layout)
        
        # 位置微调
        position_layout = QHBoxLayout()
        self.x_offset_spinbox = QSpinBox()
        self.y_offset_spinbox = QSpinBox()
        self.x_offset_spinbox.setRange(-50, 50)
        self.y_offset_spinbox.setRange(-20, 20)
        self.x_offset_spinbox.setValue(0)
        self.y_offset_spinbox.setValue(0)
        self.x_offset_spinbox.setSuffix(" px")
        self.y_offset_spinbox.setSuffix(" px")
        
        position_layout.addWidget(QLabel("X偏移:"))
        position_layout.addWidget(self.x_offset_spinbox)
        position_layout.addWidget(QLabel("Y偏移:"))
        position_layout.addWidget(self.y_offset_spinbox)
        position_layout.addStretch()
        
        params_layout.addRow("位置偏移:", position_layout)
        
        # 对比度增强
        self.contrast_checkbox = QCheckBox("启用对比度增强")
        self.contrast_checkbox.setChecked(self.style_params.get('contrast', 0) > 150)
        params_layout.addRow("增强选项:", self.contrast_checkbox)
        
        # 阴影效果
        shadow_layout = QHBoxLayout()
        self.shadow_checkbox = QCheckBox("添加文字阴影")
        self.shadow_offset_spinbox = QSpinBox()
        self.shadow_offset_spinbox.setRange(0, 5)
        self.shadow_offset_spinbox.setValue(1)
        self.shadow_offset_spinbox.setSuffix(" px")
        self.shadow_offset_spinbox.setEnabled(False)
        
        shadow_layout.addWidget(self.shadow_checkbox)
        shadow_layout.addWidget(QLabel("偏移:"))
        shadow_layout.addWidget(self.shadow_offset_spinbox)
        shadow_layout.addStretch()
        
        params_layout.addRow("阴影效果:", shadow_layout)
        
        layout.addWidget(params_group)
        
        # 预览区域
        preview_group = QGroupBox("效果预览")
        preview_layout = QVBoxLayout(preview_group)
        
        self.preview_label = QLabel("样式预览: 2025-01-01 00点至2025-01-01 17点")
        self.preview_label.setMinimumHeight(60)
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setStyleSheet("border: 1px solid #ccc; padding: 10px;")
        preview_layout.addWidget(self.preview_label)
        
        layout.addWidget(preview_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        
        self.preview_button = QPushButton("更新预览")
        self.preview_button.clicked.connect(self.update_preview)
        button_layout.addWidget(self.preview_button)
        
        self.live_preview_button = QPushButton("实时预览到原图")
        self.live_preview_button.clicked.connect(self.toggle_live_preview)
        self.live_preview_button.setCheckable(True)
        button_layout.addWidget(self.live_preview_button)
        
        self.reset_button = QPushButton("重置参数")
        self.reset_button.clicked.connect(self.reset_params)
        button_layout.addWidget(self.reset_button)
        
        button_layout.addStretch()
        
        self.ok_button = QPushButton("确认应用")
        self.ok_button.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_button)
        
        self.cancel_button = QPushButton("取消")
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        
        # 连接颜色变化事件
        for spinbox in [self.bg_r_spinbox, self.bg_g_spinbox, self.bg_b_spinbox]:
            spinbox.valueChanged.connect(self.update_bg_color_preview)
            spinbox.valueChanged.connect(self.on_param_changed)
        
        for spinbox in [self.text_r_spinbox, self.text_g_spinbox, self.text_b_spinbox]:
            spinbox.valueChanged.connect(self.update_text_color_preview)
            spinbox.valueChanged.connect(self.on_param_changed)
            
        # 连接所有参数变化事件
        self.font_size_spinbox.valueChanged.connect(self.on_param_changed)
        self.font_weight_combo.currentIndexChanged.connect(self.on_param_changed)
        self.x_offset_spinbox.valueChanged.connect(self.on_param_changed)
        self.y_offset_spinbox.valueChanged.connect(self.on_param_changed)
        self.contrast_checkbox.toggled.connect(self.on_param_changed)
        self.shadow_checkbox.toggled.connect(self.on_param_changed)
        self.shadow_offset_spinbox.valueChanged.connect(self.on_param_changed)
            
        self.shadow_checkbox.toggled.connect(self.shadow_offset_spinbox.setEnabled)
        
        # 初始化预览
        self.update_preview()
        
        # 预览状态
        self.live_preview_enabled = False
        
    def update_bg_color_preview(self):
        """更新背景色预览"""
        r = self.bg_r_spinbox.value()
        g = self.bg_g_spinbox.value()
        b = self.bg_b_spinbox.value()
        self.bg_preview.setStyleSheet(f"background-color: rgb({r}, {g}, {b}); border: 1px solid #ccc;")
        
    def update_text_color_preview(self):
        """更新文字色预览"""
        r = self.text_r_spinbox.value()
        g = self.text_g_spinbox.value()
        b = self.text_b_spinbox.value()
        self.text_preview.setStyleSheet(f"background-color: rgb({r}, {g}, {b}); border: 1px solid #ccc;")
        
    def update_preview(self):
        """更新整体预览"""
        bg_color = f"rgb({self.bg_r_spinbox.value()}, {self.bg_g_spinbox.value()}, {self.bg_b_spinbox.value()})"
        text_color = f"rgb({self.text_r_spinbox.value()}, {self.text_g_spinbox.value()}, {self.text_b_spinbox.value()})"
        font_size = self.font_size_spinbox.value()
        
        # 字体粗细映射
        weight_map = {
            0: "300",  # Light
            1: "400",  # Normal
            2: "600",  # Semi-Bold
            3: "700",  # Bold
            4: "900"   # Extra-Bold
        }
        font_weight = weight_map.get(self.font_weight_combo.currentIndex(), "400")
        
        # 阴影效果
        shadow_style = ""
        if self.shadow_checkbox.isChecked():
            offset = self.shadow_offset_spinbox.value()
            shadow_style = f"text-shadow: {offset}px {offset}px 2px rgba(0,0,0,0.3);"
        
        style = f"""
            background-color: {bg_color}; 
            color: {text_color}; 
            font-size: {font_size}px; 
            font-weight: {font_weight};
            border: 1px solid #ccc; 
            padding: 10px;
            {shadow_style}
        """
        
        self.preview_label.setStyleSheet(style)
        
    def reset_params(self):
        """重置为原始参数"""
        self.font_size_spinbox.setValue(self.style_params['font_size'])
        self.font_weight_combo.setCurrentIndex(1)
        
        self.bg_r_spinbox.setValue(self.style_params['bg_color'][0])
        self.bg_g_spinbox.setValue(self.style_params['bg_color'][1])
        self.bg_b_spinbox.setValue(self.style_params['bg_color'][2])
        
        self.text_r_spinbox.setValue(self.style_params['text_color'][0])
        self.text_g_spinbox.setValue(self.style_params['text_color'][1])
        self.text_b_spinbox.setValue(self.style_params['text_color'][2])
        
        self.x_offset_spinbox.setValue(0)
        self.y_offset_spinbox.setValue(0)
        self.contrast_checkbox.setChecked(self.style_params.get('contrast', 0) > 150)
        self.shadow_checkbox.setChecked(False)
        
        self.update_preview()
        
    def toggle_live_preview(self):
        """切换实时预览模式"""
        self.live_preview_enabled = self.live_preview_button.isChecked()
        
        if self.live_preview_enabled:
            # 启用实时预览
            self.live_preview_button.setText("关闭实时预览")
            self.live_preview_button.setStyleSheet("background-color: #e74c3c; color: white;")
            
            # 生成预览文本
            preview_text = self.generate_preview_text()
            
            # 获取当前参数并启动预览
            current_params = self.get_adjusted_params()
            if hasattr(self.parent(), 'start_live_preview'):
                self.parent().start_live_preview(preview_text, current_params)
        else:
            # 关闭实时预览
            self.live_preview_button.setText("实时预览到原图")
            self.live_preview_button.setStyleSheet("")
            
            if hasattr(self.parent(), 'exit_preview_mode'):
                self.parent().exit_preview_mode()
                
    def on_param_changed(self):
        """参数改变时的回调"""
        self.update_preview()  # 更新对话框内的预览
        
        if self.live_preview_enabled:
            # 更新实时预览
            preview_text = self.generate_preview_text()
            current_params = self.get_adjusted_params()
            if hasattr(self.parent(), 'update_live_preview'):
                self.parent().update_live_preview(preview_text, current_params)
                
    def generate_preview_text(self):
        """生成预览文本"""
        from datetime import datetime
        today = datetime.now().strftime('%Y-%m-%d')
        return f"{today} 00点至{today} 17点"
        
    def closeEvent(self, event):
        """对话框关闭时清理预览"""
        if self.live_preview_enabled and hasattr(self.parent(), 'exit_preview_mode'):
            self.parent().exit_preview_mode()
        super().closeEvent(event)
        
    def reject(self):
        """取消时清理预览"""
        if self.live_preview_enabled and hasattr(self.parent(), 'exit_preview_mode'):
            self.parent().exit_preview_mode()
        super().reject()
        
    def get_adjusted_params(self):
        """获取调整后的参数"""
        return {
            'bg_color': (self.bg_r_spinbox.value(), self.bg_g_spinbox.value(), self.bg_b_spinbox.value()),
            'text_color': (self.text_r_spinbox.value(), self.text_g_spinbox.value(), self.text_b_spinbox.value()),
            'font_size': self.font_size_spinbox.value(),
            'font_weight': self.font_weight_combo.currentIndex(),
            'width': self.style_params['width'],
            'height': self.style_params['height'],
            'brightness_level': self.style_params['brightness_level'],
            'contrast': self.style_params['contrast'],
            'x_offset': self.x_offset_spinbox.value(),
            'y_offset': self.y_offset_spinbox.value(),
            'enable_contrast': self.contrast_checkbox.isChecked(),
            'enable_shadow': self.shadow_checkbox.isChecked(),
            'shadow_offset': self.shadow_offset_spinbox.value()
        }


class StyleInputDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("样式参数输入")
        self.setFixedSize(500, 600)
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout(self)
        
        # 说明标签
        instruction = QLabel("请输入或粘贴样式分析结果，系统将自动解析参数：")
        layout.addWidget(instruction)
        
        # 文本输入区域
        self.text_input = QTextEdit()
        self.text_input.setPlaceholderText("在此粘贴样式分析报告，或手动输入参数...")
        layout.addWidget(self.text_input)
        
        # 参数组
        params_group = QGroupBox("解析的参数（可手动调整）")
        params_layout = QFormLayout(params_group)
        
        # 背景颜色
        self.bg_color_input = QLineEdit()
        self.bg_color_input.setPlaceholderText("例如: RGB(255, 255, 255) 或 #ffffff")
        params_layout.addRow("背景颜色:", self.bg_color_input)
        
        # 文字颜色
        self.text_color_input = QLineEdit()
        self.text_color_input.setPlaceholderText("例如: RGB(0, 0, 0) 或 #000000 或 114")
        params_layout.addRow("文字颜色:", self.text_color_input)
        
        # 字体大小
        self.font_size_input = QSpinBox()
        self.font_size_input.setRange(8, 100)
        self.font_size_input.setValue(14)
        params_layout.addRow("字体大小:", self.font_size_input)
        
        # 区域尺寸
        self.width_input = QSpinBox()
        self.width_input.setRange(1, 2000)
        self.width_input.setValue(200)
        params_layout.addRow("区域宽度:", self.width_input)
        
        self.height_input = QSpinBox()
        self.height_input.setRange(1, 200)
        self.height_input.setValue(30)
        params_layout.addRow("区域高度:", self.height_input)
        
        # 亮度级别
        self.brightness_combo = QComboBox()
        self.brightness_combo.addItems(["dark", "medium", "bright"])
        self.brightness_combo.setCurrentText("bright")
        params_layout.addRow("亮度级别:", self.brightness_combo)
        
        # 对比度
        self.contrast_input = QSpinBox()
        self.contrast_input.setRange(0, 255)
        self.contrast_input.setValue(100)
        params_layout.addRow("对比度:", self.contrast_input)
        
        layout.addWidget(params_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        
        self.parse_button = QPushButton("解析文本")
        self.parse_button.clicked.connect(self.parse_style_text)
        button_layout.addWidget(self.parse_button)
        
        self.ok_button = QPushButton("确定")
        self.ok_button.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_button)
        
        self.cancel_button = QPushButton("取消")
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        
    def parse_style_text(self):
        """解析粘贴的样式文本"""
        text = self.text_input.toPlainText()
        
        try:
            # 解析RGB颜色
            rgb_pattern = r'RGB\((\d+),\s*(\d+),\s*(\d+)\)'
            rgb_matches = re.findall(rgb_pattern, text)
            
            # 解析十六进制颜色
            hex_pattern = r'#([0-9a-fA-F]{6})'
            hex_matches = re.findall(hex_pattern, text)
            
            # 解析数字参数
            font_size_match = re.search(r'建议字体大小[:\s]*(\d+)px', text)
            width_match = re.search(r'区域尺寸[:\s]*(\d+)\s*[×x]\s*(\d+)', text)
            brightness_match = re.search(r'平均亮度[:\s]*([0-9.]+)', text)
            contrast_match = re.search(r'对比度[:\s]*(\d+)', text)
            text_color_match = re.search(r'建议文字颜色[:\s]*(\d+)', text)
            
            # 设置背景颜色（通常是第一个RGB值）
            if rgb_matches:
                bg_rgb = rgb_matches[0]
                self.bg_color_input.setText(f"RGB({bg_rgb[0]}, {bg_rgb[1]}, {bg_rgb[2]})")
            elif hex_matches:
                self.bg_color_input.setText(f"#{hex_matches[0]}")
                
            # 设置文字颜色
            if text_color_match:
                self.text_color_input.setText(text_color_match.group(1))
            elif len(rgb_matches) > 1:
                text_rgb = rgb_matches[1]
                self.text_color_input.setText(f"RGB({text_rgb[0]}, {text_rgb[1]}, {text_rgb[2]})")
                
            # 设置字体大小
            if font_size_match:
                self.font_size_input.setValue(int(font_size_match.group(1)))
                
            # 设置区域尺寸
            if width_match:
                self.width_input.setValue(int(width_match.group(1)))
                self.height_input.setValue(int(width_match.group(2)))
                
            # 设置亮度级别
            if brightness_match:
                brightness_val = float(brightness_match.group(1))
                if brightness_val < 85:
                    self.brightness_combo.setCurrentText("dark")
                elif brightness_val < 170:
                    self.brightness_combo.setCurrentText("medium")
                else:
                    self.brightness_combo.setCurrentText("bright")
                    
            # 设置对比度
            if contrast_match:
                self.contrast_input.setValue(int(contrast_match.group(1)))
                
            QMessageBox.information(self, "解析完成", "样式参数已自动填入，请检查并调整")
            
        except Exception as e:
            QMessageBox.warning(self, "解析错误", f"解析样式文本时出错: {str(e)}")
    
    def get_style_params(self):
        """获取样式参数"""
        return {
            'bg_color': self.parse_color(self.bg_color_input.text()),
            'text_color': self.parse_color(self.text_color_input.text()),
            'font_size': self.font_size_input.value(),
            'width': self.width_input.value(),
            'height': self.height_input.value(),
            'brightness_level': self.brightness_combo.currentText(),
            'contrast': self.contrast_input.value()
        }
    
    def parse_color(self, color_text):
        """解析颜色文本为RGB元组"""
        color_text = color_text.strip()
        
        # RGB格式
        rgb_match = re.match(r'RGB\((\d+),\s*(\d+),\s*(\d+)\)', color_text)
        if rgb_match:
            return (int(rgb_match.group(1)), int(rgb_match.group(2)), int(rgb_match.group(3)))
        
        # 十六进制格式
        hex_match = re.match(r'#([0-9a-fA-F]{6})', color_text)
        if hex_match:
            hex_val = hex_match.group(1)
            return (int(hex_val[0:2], 16), int(hex_val[2:4], 16), int(hex_val[4:6], 16))
        
        # 单个数字（灰度值）
        if color_text.isdigit():
            val = int(color_text)
            return (val, val, val)
        
        # 默认返回黑色
        return (0, 0, 0)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = DateReplacerApp()
    ex.show()
    sys.exit(app.exec_())